package com.shanpin.shebao.web.module.rong360;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import net.sf.json.JSONObject;

import org.eclipse.jetty.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.shanpin.core.http.MJsonView;
import com.shanpin.core.utils.DateUtil;
import com.shanpin.core.utils.JsonUtil;
import com.shanpin.shebao.web.module.rong360.constant.Constant;
import com.shanpin.shebao.web.module.rong360.constant.State;
import com.shanpin.shebao.web.module.rong360.constant.Type;
import com.shanpin.shebao.web.module.rong360.model.TianjiFundResponse;
import com.shanpin.shebao.web.module.rong360.model.TianjiFundResponseFormat;
import com.shanpin.shebao.web.module.rong360.model.TianjiInsureResponse;
import com.shanpin.shebao.web.module.rong360.model.TianjiInsureResponseFormat;
import com.shanpin.shebao.web.module.rong360.model.TianjiRequest;
import com.shanpin.shebao.web.module.rong360.model.TianjiResponseFormat;
import com.shanpin.shebao.web.module.rong360.sdk.sample.OpenapiClient;
import com.shanpin.shebao.web.module.rong360.sdk.utils.RequestUtil;
import com.shanpin.shebao.web.service.CacheService;

/**
 * 融360天机查询
 * 1、查询用户公积金信息
 *	2、查询用户社保信息
 */
@Controller
@RequestMapping("/tianji")
public class TianjiController {
	
	private static Logger logger = LoggerFactory.getLogger(TianjiController.class);
	
	private static AtomicInteger IDX = new AtomicInteger(0);
	
	@Autowired
	private CacheService cacheService;
	@Autowired
	private TianjiService tianjiService;

	@RequestMapping(value="/collectUser", method=RequestMethod.GET)
	public String collectUser(String userId, String type, String channel){
		Type t = Type.of(type);
		if(t == null) {
			logger.warn("rong360-collectUser unknow type {}", type);
			t = Type.insure;
		}
		OpenapiClient client = new OpenapiClient();
		client.setAppId(Constant.APPID);
		client.setPrivateKey(Constant.PRIVATE_KEY); 
		client.setIsTestEnv(false);
		client.setPrintLog(false);
		client.setLogid(RequestUtil.generateLogid());

		client.setMethod("tianji.api.tianjireport.collectuser");
		client.setField("type", t.getCode());
		client.setField("platform", "web");	
		client.setField("name", Constant.DEFAULT_NAME);
		client.setField("idNumber", Constant.DEFAULT_IDCARD);
		client.setField("phone", Constant.DEFAULT_PHONE);
		
		if(StringUtil.isBlank(userId)) {
			//游客默认用户编号
			userId = "99999999";
		}
		String outUniqueId = DateUtil.dateMills()+String.format("%03d", IDX.getAndIncrement()%1000)+userId;
		client.setField("userId", userId);
		client.setField("outUniqueId", outUniqueId);
		client.setField("notifyUrl", Constant.NOTIFY_URL);
		client.setField("returnUrl", Constant.RETURN_URL);
		
		TianjiRequest req = new TianjiRequest();
		req.setOutUniqueId(outUniqueId);
		req.setChannel(channel);
		req.setType(t);
		req.setState(State.init);
		cacheService.tianjiRequestCache(outUniqueId, req);
		try {
			JSONObject ret = client.execute();
			if(ret.getInt("error") != 200) {
				logger.warn("rong360 collectUser error", ret.getString("msg"));
				req.setState(State.fail);
				return "tianji/"+t.getCode();
			}
			JSONObject data = ret.getJSONObject("tianji_api_tianjireport_collectuser_response");
			String redirectUrl = data.getString("redirectUrl");
			return "redirect:"+redirectUrl;
		} catch (Exception e) {
			logger.error("rong360 collectUser error", e);
			req.setState(State.fail);
			return "tianji/"+t.getCode();
		}
	}
	
	@RequestMapping(value="/returnUrl", method=RequestMethod.GET)
	public ModelAndView returnUrl(String userId, String outUniqueId, String state){
		ModelAndView mv = new ModelAndView();
		TianjiRequest req = cacheService.getTianjiRequest(outUniqueId);
		if(req == null) {
			mv.setViewName("tianji/insure");
			return mv;
		}
		Type type = req.getType();
		mv.setViewName("tianji/"+type.getCode());
		mv.addObject("userId", userId);
		mv.addObject("outUniqueId", outUniqueId);
		mv.addObject("channel", req.getChannel());
		mv.addObject("state", state);
		return mv;
	}
	
	@RequestMapping(value="/notifyUrl", method=RequestMethod.POST)
	public String notifyUrl(String userId, String outUniqueId, String state, 
			String account, String search_id, String accountType, String errorReasonDetail){
		TianjiRequest req = cacheService.getTianjiRequest(outUniqueId);
		if(req == null) {
			return "fail";
		}
		req.setState(State.of(state));
		
		String dataStr = null;
		if(req.getState()==State.crawl  || req.getState()==State.report) {
			OpenapiClient client = new OpenapiClient();
			client.setAppId(Constant.APPID);
			client.setPrivateKey(Constant.PRIVATE_KEY); 
			client.setIsTestEnv(false);
			client.setPrintLog(false);
			client.setLogid(RequestUtil.generateLogid());

			client.setField("user_id", search_id);
			client.setField("merchant_id", Constant.APPID);
			Type type = req.getType();
			if(type==Type.insure) {
				client.setMethod("wd.api.insure.getDataV2");
				try {
					JSONObject ret = client.execute();
					JSONObject response = ret.getJSONObject("wd_api_insure_getDataV2_response");
					JSONObject data = response.getJSONObject("data");
					dataStr = data.toString();
					
					TianjiInsureResponse resp = JsonUtil.toT(dataStr, TianjiInsureResponse.class);
					TianjiInsureResponseFormat format = resp.format();
					List<TianjiInsureResponse.Data> dataList = resp.getData_list();
					if(dataList.size()>0 
							&& dataList.get(0).getUser() != null
							&& format != null) {
						TianjiInsureResponse.User user = dataList.get(0).getUser();
						int uid = Integer.parseInt(userId);
						String idcard = user.getId_card();
						if(Constant.DEFAULT_IDCARD.equals(idcard)) {
							idcard = null;
						}
						String city = user.getInsure_city();
						String name = user.getReal_name();
						if(Constant.DEFAULT_NAME.equals(name)) {
							name = null;
						}
						String phone = user.getCellphone();
						if(StringUtil.isBlank(phone)) {
							phone = user.getPhone();
						}
						if(Constant.DEFAULT_PHONE.equals(phone)) {
							phone = null;
						}
						String insureComName = user.getCom_name();
						String insureComCode = user.getCom_code();
						int insurePer = 0;
						if(StringUtil.isNotBlank(format.getPer_rmb())) {
							insurePer = (int)(Double.parseDouble(format.getPer_rmb())*100);
						}
						int insureCom = 0;
						if(StringUtil.isNotBlank(format.getCom_rmb())) {
							insureCom = (int)(Double.parseDouble(format.getCom_rmb())*100);
						}
						String insureBeginMonth = format.getBegin_month();
						String insureEndMonth = format.getEnd_month();
						String insurePensionLackMonth = format.getPension_lack_month_detail();
						String insureMedicalLackMonth = format.getMedical_lack_month_detail();
						boolean r = tianjiService.saveOrUpdateInsure(uid, idcard, city, name, phone, 
								insureComName, insureComCode, insurePer, insureCom, insureBeginMonth, insureEndMonth, insurePensionLackMonth, insureMedicalLackMonth);
						if(!r) {
							logger.warn("rong360 insure save fail");
						}
					}
					req.setResponse(format);
					req.setState(State.finish);
				} catch (Exception e) {
					req.setState(State.fail);
					logger.warn("rong360 insure notify {}-{}", type.getCode(), dataStr, e);
					return "fail";
				}
			} else if(type==Type.fund) {
				client.setMethod("wd.api.fund.getDataV2");
				try {
					JSONObject ret = client.execute();
					JSONObject response = ret.getJSONObject("wd_api_fund_getDataV2_response");
					JSONObject data = response.getJSONObject("data");
					dataStr = data.toString();
					
					TianjiFundResponse resp = JsonUtil.toT(dataStr, TianjiFundResponse.class);
					TianjiFundResponseFormat format = resp.format();
					List<TianjiFundResponse.Data> dataList = resp.getData_list();
					if(dataList.size()>0 
							&& dataList.get(0).getUser() != null
							&& format != null) {
						TianjiFundResponse.User user = dataList.get(0).getUser();
						int uid = Integer.parseInt(userId);
						String idcard = user.getId_card();
						if(Constant.DEFAULT_IDCARD.equals(idcard)) {
							idcard = null;
						}
						String city = user.getFund_city();
						String name = user.getReal_name();
						if(Constant.DEFAULT_NAME.equals(name)) {
							name = null;
						}
						String phone = user.getCellphone();
						if(StringUtil.isBlank(phone)) {
							phone = user.getPhone();
						}
						if(Constant.DEFAULT_PHONE.equals(phone)) {
							phone = null;
						}
						String fundComName = user.getCom_name();
						String fundComCode = user.getCom_code();
						int fundBaseMoney = 0;
						if(StringUtil.isNotBlank(format.getFund_base_money())) {
							fundBaseMoney = (int)(Double.parseDouble(format.getFund_base_money())*100);
						}
						int fundMonthMoney = 0;
						if(StringUtil.isNotBlank(format.getFund_month_money())) {
							fundMonthMoney = (int)(Double.parseDouble(format.getFund_month_money())*100);
						}
						int fundPer = 0;
						if(StringUtil.isNotBlank(format.getPer_rmb())) {
							fundPer = (int)(Double.parseDouble(format.getPer_rmb())*100);
						}
						int fundCom = 0;
						if(StringUtil.isNotBlank(format.getCom_rmb())) {
							fundCom = (int)(Double.parseDouble(format.getCom_rmb())*100);
						}
						String fundBeginMonth = format.getBegin_month();
						String fundEndMonth = format.getEnd_month();
						String fundLackMonth = format.getLack_month_detail();
						boolean r = tianjiService.saveOrUpdateFund(uid, idcard, city, name, phone, 
								fundComName, fundComCode, fundBaseMoney, fundMonthMoney, fundPer, fundCom, fundBeginMonth, fundEndMonth, fundLackMonth);
						if(!r) {
							logger.warn("rong360 fund save fail");
						}
					}
					req.setResponse(format);
					req.setState(State.finish);
				} catch (Exception e) {
					req.setState(State.fail);
					logger.warn("rong360 fund notify {}-{}", type.getCode(), dataStr, e);
					return "fail";
				}
			}
		}
		return "success";
	}
	
	@RequestMapping(value="/queryResult", method=RequestMethod.GET)
	public ModelAndView queryResult(String outUniqueId) {
		TianjiRequest req = cacheService.getTianjiRequest(outUniqueId);
		if(req == null) {
			return MJsonView.fail("请求已过期");
		}
		if(req.getState()==State.crawl_fail  || req.getState()==State.report_fail) {
			return MJsonView.fail("接口繁忙,稍后重试");
		}
		if(req.getState() == State.fail) {
			return MJsonView.fail("接口异常");
		}
		if(req.getState()==State.finish) {
			TianjiResponseFormat response = req.getResponse();
			return MJsonView.ok(response);
		}
		return MJsonView.ok();
	}
	
	@RequestMapping(value="/test", method=RequestMethod.GET)
	public ModelAndView test(String type, String outUniqueId, String filename) throws Exception{
		BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("/home/chensenlai/下载/pinpin/"+filename)));
		String cont = "";
		String line = null;
		while( (line=br.readLine())!=null ) {
			cont += line;
		}
		br.close();
		
		TianjiRequest req = new TianjiRequest();
		req.setOutUniqueId(outUniqueId);
		req.setChannel("test");
		req.setType(Type.of(type));
		req.setState(State.finish);
		
		if(Type.of(type) == Type.insure) {
			TianjiInsureResponse resp = JsonUtil.toT(cont, TianjiInsureResponse.class);
			TianjiInsureResponseFormat format = resp.format();
			req.setResponse(format);
		} else {
			TianjiFundResponse resp = JsonUtil.toT(cont, TianjiFundResponse.class);
			TianjiFundResponseFormat format = resp.format();
			req.setResponse(format);
		}
		
		cacheService.tianjiRequestCache(outUniqueId, req);
		
		ModelAndView mv = new ModelAndView();
		mv.setViewName("tianji/"+type);
		mv.addObject("userId", "123456");
		mv.addObject("outUniqueId", outUniqueId);
		mv.addObject("channel", req.getChannel());
		mv.addObject("state", State.finish.getCode());
		return mv;
	}
}
